<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${title} + ' - 王氏美容汽车集团管理系统'">客户统计分析 - 王氏美容汽车集团管理系统</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        .dashboard-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: transform 0.2s;
        }
        .dashboard-card:hover {
            transform: translateY(-5px);
        }
        .chart-container {
            position: relative;
            height: 400px;
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
        }
    </style>
</head>
<body class="bg-light">
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">
                <i class="fas fa-car me-2"></i>王氏美容汽车集团
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/dashboard">
                            <i class="fas fa-tachometer-alt me-1"></i>仪表盘
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/dashboard/customers">
                            <i class="fas fa-chart-bar me-1"></i>客户统计
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/customers">
                            <i class="fas fa-users me-1"></i>客户管理
                        </a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i>管理员
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/profile">个人资料</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="/logout">退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <!-- 页面标题 -->
        <div class="row mb-4">
            <div class="col">
                <h2><i class="fas fa-chart-bar me-2"></i>客户统计分析</h2>
                <p class="text-muted">深入分析客户数据，洞察业务趋势</p>
            </div>
            <div class="col-auto">
                <button class="btn btn-primary" onclick="refreshData()">
                    <i class="fas fa-sync-alt me-2"></i>刷新数据
                </button>
            </div>
        </div>

        <!-- 统计概览 -->
        <div class="row mb-4">
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <i class="fas fa-users fa-3x mb-3"></i>
                        <h3 class="mb-1" id="totalCustomers">-</h3>
                        <p class="mb-0">总客户数</p>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <i class="fas fa-user-plus fa-3x mb-3"></i>
                        <h3 class="mb-1" id="newCustomers">-</h3>
                        <p class="mb-0">本月新增</p>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <i class="fas fa-heart fa-3x mb-3"></i>
                        <h3 class="mb-1" id="activeCustomers">-</h3>
                        <p class="mb-0">活跃客户</p>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <i class="fas fa-wallet fa-3x mb-3"></i>
                        <h3 class="mb-1" id="totalBalance">-</h3>
                        <p class="mb-0">总余额(万元)</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div class="row mb-4">
            <!-- 会员等级分布 -->
            <div class="col-lg-6 mb-3">
                <div class="card dashboard-card">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-chart-pie me-2"></i>会员等级分布
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="memberLevelChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 客户增长趋势 -->
            <div class="col-lg-6 mb-3">
                <div class="card dashboard-card">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-chart-line me-2"></i>客户增长趋势
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="customerGrowthChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 排行榜 -->
        <div class="row mb-4">
            <!-- 余额排行榜 -->
            <div class="col-lg-4 mb-3">
                <div class="card dashboard-card">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-trophy me-2"></i>余额排行榜
                        </h5>
                    </div>
                    <div class="card-body">
                        <div id="balanceRanking" class="list-group list-group-flush">
                            <div class="text-center text-muted">
                                <i class="fas fa-spinner fa-spin"></i> 加载中...
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 积分排行榜 -->
            <div class="col-lg-4 mb-3">
                <div class="card dashboard-card">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-star me-2"></i>积分排行榜
                        </h5>
                    </div>
                    <div class="card-body">
                        <div id="pointsRanking" class="list-group list-group-flush">
                            <div class="text-center text-muted">
                                <i class="fas fa-spinner fa-spin"></i> 加载中...
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 消费排行榜 -->
            <div class="col-lg-4 mb-3">
                <div class="card dashboard-card">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-shopping-cart me-2"></i>消费排行榜
                        </h5>
                    </div>
                    <div class="card-body">
                        <div id="consumptionRanking" class="list-group list-group-flush">
                            <div class="text-center text-muted">
                                <i class="fas fa-spinner fa-spin"></i> 加载中...
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- 页面脚本 -->
    <script>
        let memberLevelChart, customerGrowthChart;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initCharts();
            loadData();
        });

        // 初始化图表
        function initCharts() {
            // 会员等级分布图表
            const memberLevelCtx = document.getElementById('memberLevelChart').getContext('2d');
            memberLevelChart = new Chart(memberLevelCtx, {
                type: 'doughnut',
                data: {
                    labels: ['普通会员', '银卡会员', '金卡会员', 'VIP会员'],
                    datasets: [{
                        data: [0, 0, 0, 0],
                        backgroundColor: [
                            '#6c757d',
                            '#6f42c1', 
                            '#fd7e14',
                            '#dc3545'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });

            // 客户增长趋势图表
            const customerGrowthCtx = document.getElementById('customerGrowthChart').getContext('2d');
            customerGrowthChart = new Chart(customerGrowthCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: '新增客户',
                        data: [],
                        borderColor: 'rgb(75, 192, 192)',
                        backgroundColor: 'rgba(75, 192, 192, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        // 加载数据
        function loadData() {
            // 加载概览数据
            fetch('/dashboard/api/overview')
                .then(response => response.json())
                .then(data => {
                    const customers = data.customers || {};
                    document.getElementById('totalCustomers').textContent = customers.total || 0;
                    document.getElementById('newCustomers').textContent = customers.monthNew || 0;
                    document.getElementById('activeCustomers').textContent = customers.activeCount || 0;
                    document.getElementById('totalBalance').textContent = 
                        ((customers.totalBalance || 0) / 10000).toFixed(1);
                })
                .catch(error => console.error('加载概览数据失败:', error));

            // 加载图表数据
            fetch('/dashboard/api/customer-charts')
                .then(response => response.json())
                .then(data => {
                    // 更新会员等级分布图表
                    if (data.memberLevelDistribution) {
                        const levels = data.memberLevelDistribution.map(item => item[0]);
                        const counts = data.memberLevelDistribution.map(item => item[1]);
                        memberLevelChart.data.labels = levels;
                        memberLevelChart.data.datasets[0].data = counts;
                        memberLevelChart.update();
                    }

                    // 更新排行榜
                    updateRanking('balanceRanking', data.balanceRanking, 'balance', '余额');
                    updateRanking('pointsRanking', data.pointsRanking, 'points', '积分');
                    updateRanking('consumptionRanking', data.consumptionRanking, 'totalConsumption', '消费');
                })
                .catch(error => console.error('加载图表数据失败:', error));
        }

        // 更新排行榜
        function updateRanking(containerId, data, field, unit) {
            const container = document.getElementById(containerId);
            if (!data || data.length === 0) {
                container.innerHTML = '<div class="text-center text-muted">暂无数据</div>';
                return;
            }

            let html = '';
            data.slice(0, 10).forEach((customer, index) => {
                const value = customer[field] || 0;
                const formattedValue = field === 'balance' || field === 'totalConsumption' 
                    ? '¥' + value.toFixed(2) 
                    : value.toString();
                
                html += `
                    <div class="list-group-item d-flex justify-content-between align-items-center">
                        <div>
                            <span class="badge bg-primary rounded-pill me-2">${index + 1}</span>
                            <strong>${customer.name}</strong>
                            <small class="text-muted d-block">${customer.phone}</small>
                        </div>
                        <span class="badge bg-success">${formattedValue}</span>
                    </div>
                `;
            });
            container.innerHTML = html;
        }

        // 刷新数据
        function refreshData() {
            loadData();
        }

        // 定时刷新数据
        setInterval(refreshData, 60000); // 每分钟刷新一次
    </script>
</body>
</html>
